package com.cleverest.cleverestdiary.controller;

import com.cleverest.cleverestdiary.pojo.Result;
import com.cleverest.cleverestdiary.service.FileService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException, NoSuchAlgorithmException {
        String bucketName = "diary";
        String fileName = fileService.renameFile(file);
        System.out.println(fileName);
        // 检查文件大小（可选）
        if (file.getSize() > 1000 * 1024 * 1024) { // 1000MB
            return Result.error("文件大小不能超过1000MB");
        }

        // 目标 URL
        String targetUrl = "http://211.101.233.71:8083/netdisk/api/upload";
        // 构建请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", file.getResource());
        body.add("fileName", fileName);
        body.add("bucketName", bucketName);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);

        // 创建 HttpEntity 封装请求头和请求体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 发送 POST 请求到目标服务器
        ResponseEntity<String> response = restTemplate.exchange(targetUrl, HttpMethod.POST, (org.springframework.http.HttpEntity<?>) requestEntity, String.class);

// 判断响应是否成功
        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();  // 获取响应体作为字符串

            // 使用 Jackson 解析 JSON 响应体
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(responseBody);

                // 获取 code 和 msg 字段
                int code = rootNode.path("code").asInt();
                String msg = rootNode.path("msg").asText();

                // 根据 code 和 msg 决定返回的内容
                if (code == 200 && "上传成功".equals(msg)) {
                    String fileUrl = getFileUrl(fileName).getData();
//                    System.out.println(fileUrl);
                    return Result.success(fileUrl);  // 直接返回 URL 字符串
                } else if (code == 404 && "文件已经存在！".equals(msg)) {
                    String fileUrl = getFileUrl(fileName).getData();
//                    System.out.println(fileUrl);
                    return Result.success(fileUrl);  // 直接返回 URL 字符串
                } else if (code == 404 && "上传失败".equals(msg)) {
                    return Result.error(msg);  // 返回错误消息
                } else {
                    return Result.error("未知的响应: " + responseBody);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error("响应体解析失败: " + e.getMessage());
            }
        } else {
            return Result.error("请求失败，状态码: " + response.getStatusCode().value());
        }
    }

    @GetMapping("/getUrl")
    public Result<String> getFileUrl(String fileName) {
        // 构建请求URL
        String apiUrl = "http://211.101.233.71:8083/netdisk/api/getUrl";
        String bucketName = "diary";
        String urlString = apiUrl + "?fileName=" + fileName + "&bucketName=" + bucketName;

        try {
            // 创建URL对象
            URL url = new URL(urlString);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 200
                // 读取响应内容
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 解析JSON响应
                String jsonResponse = response.toString();
                // 假设响应格式为：{"msg":"success","code":200,"data":{"FileUrl":"http://example.com/file"}}
                if (jsonResponse.contains("\"code\":200")) {
                    // 提取FileUrl
                    int startIndex = jsonResponse.indexOf("\"FileUrl\":\"") + 11;
                    int endIndex = jsonResponse.indexOf("\"", startIndex);
                    String fileUrl = jsonResponse.substring(startIndex, endIndex);

                    // 返回成功结果，包含文件URL
                    return Result.success(fileUrl);
                } else {
                    // 返回错误结果，包含外部API的错误信息
                    return Result.error("外部API返回错误: " + jsonResponse);
                }
            } else {
                // 返回HTTP错误结果
                return Result.error("HTTP请求失败，状态码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 返回异常结果
            return Result.error("请求异常: " + e.getMessage());
        }
    }
}